<template>
  <div v-loading="loading" class="app-container">
    <!-- 挂号编号的查询条件开始 -->
    <el-form ref="queryForm" label-width="88px">
      <el-form-item label="挂号单ID" prop="regId">
        <el-input
            v-model="regId"
            clearable
            placeholder="请输入挂号单号"
            size="small"
            style="width:300px"
        />
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleReadICCard">读取IC卡</el-button>
      </el-form-item>
    </el-form>
    <!-- 挂号编号的查询条件结束 -->

    <!-- 挂号输入框下面的所有内容开始 -->
    <div v-if="careHistory && careHistory.regId">
      <!-- 病例信息开始 -->
      <el-card style="margin-bottom: 5px">
        <el-form label-position="right" label-width="120px" inline class="demo-table-expand">
          <el-form-item label="挂号单号:">
            <span>{{ careHistory.regId }}</span>
          </el-form-item>
          <el-form-item label="医生姓名:">
            <span>{{ careHistory.userName }}</span>
          </el-form-item>
          <el-form-item label="科室名称:">
            <span>{{ careHistory.deptName }}</span>
          </el-form-item>
          <el-form-item label="患者姓名:">
            <span>{{ careHistory.patientName }}</span>
          </el-form-item>
          <el-form-item label="就诊时间:">
            <span>{{ careHistory.careTime }}</span>
          </el-form-item>
          <el-form-item label="主诉:">
            <span>{{ careHistory.caseTitle }}</span>
          </el-form-item>
          <el-form-item label="诊断信息:">
            <span>{{ careHistory.caseResult }}</span>
          </el-form-item>
          <el-form-item label="医生建议:">
            <span>{{ careHistory.doctorTips }}</span>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 病例信息结束 -->

      <!-- 工具按钮开始 -->
      <el-card style="margin-bottom: 5px">
        <el-button type="success" icon="el-icon-finished" @click="handleSelectAll">全选</el-button>
        <el-button type="success" icon="el-icon-finished" @click="handleUnSelectAll">取消全选</el-button>
        <el-button type="danger" icon="el-icon-bank-card" @click="handlePayWithCash">现金支付</el-button>
        <el-button type="danger" icon="el-icon-bank-card" @click="handlePayWithWx">微信支付</el-button>
        <span style="margin-left:20px">订单总额:<span style="color:red;margin-left:20px">￥:{{ allAmount }}</span></span>
      </el-card>
      <!-- 工具按钮结束 -->

      <!-- 未支付的处方信息开始 -->
      <el-card style="margin-bottom: 5px">
        <el-collapse v-if="careOrders && careOrders.length > 0" v-model="activeNames">
          <el-collapse-item v-for="(item, index) in careOrders" :key="index" :name="index">
            <template slot="title">
              【药用处方】【{{ index + 1 }}】【处方总额】:￥{{ item.allAmount }}
            </template>
            <el-table
                ref="refTable"
                v-loading="loading"
                border
                :data="item.careOrderItems"
                :row-class-name="tableRowClassName"
                @selection-change="handleCareOrderItemSelectionChange($event, item.coId)"
            >
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="序号" align="center" type="index" width="50"/>
              <el-table-column label="药品名称" align="center" prop="itemName"/>
              <el-table-column label="数量" align="center" prop="num"/>
              <el-table-column label="单价(元)" align="center" prop="price"/>
              <el-table-column label="金额(元)" align="center" prop="amount"/>
              <el-table-column label="备注" align="center" prop="remark"/>
              <el-table-column label="状态" align="center" prop="status" :formatter="statusFormatter"/>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-card>
      <!-- 未支付的处方信息结束 -->
    </div>

    <div v-else style="text-align:center">温馨提示：请输入正确的挂号单ID查询</div>

    <!-- 微信支付弹窗 -->
    <el-dialog
        title="请使用微信支付"
        :visible.sync="openPay"
        width="30%"
        :before-close="handleClose"
    >
      <div style="text-align: center">
        <p v-if="payResult.orderAmount">微信支付{{ payResult.orderAmount }}元</p>
        <div style="border: 1px solid #f3f3f3; width: 220px; padding: 10px; margin: 0px auto">
          <vue-qr
              v-show="payResult.codeUrl"
              :text="payResult.codeUrl"
              :margin="0"
              :logoSrc="require('@/assets/logo.jpg')"
              colorDark="green"
              :size="200"
              colorLight="white"
          ></vue-qr>
        </div>
        <!-- 倒计时显示 -->

      </div>
      <el-divider></el-divider>
      <div style="font-size: 13px">
        提示:<br>
        支付成功前请勿手动关闭页面<br>
        二维码三十秒内有效，请及时扫码<br>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VueQr from 'vue-qr'

export default {
  components: {
    VueQr
  },
  data() {
    return {
      loading: false, // 页面加载状态
      loadingText: '', // 加载文本提示
      regId: '', // 挂号单ID输入框的值
      careHistory: {}, // 存储查询到的病例信息
      payStatusOptions: [], // 支付状态选项
      careOrders: [], // 未支付的处方订单列表
      activeNames: [], // 展开的处方列表
      itemObjs: [], // 用户选中的处方项目
      allAmount: 0,  // 订单总金额
      payObj: {
        orderId:"" // 订单ID
      },
      openPay: false, // 是否打开微信支付二维码弹窗
      intervalObj: undefined, // 定时轮询对象，用于查询支付状态
      payResult: {
        orderAmount: 0, // 支付金额
        codeUrl: "", // 微信支付二维码URL
        orderNo: "" // 订单号
      },
      autoCloseTimer: null, // 自动关闭计时器
      countdownTimer: null, // 倒计时计时器
      countdown: 30 // 倒计时初始化为30秒
    }
  },
  created() {
    this.StatusName(); // 在组件创建时加载支付状态字典
  },
  methods: {
    // 处理查询按钮的点击事件
    handleQuery() {
      if (!this.regId) {
        this.$message.warning('请输入挂号单号');
        this.resetCurrentParams(); // 如果输入为空则重置当前数据
        return;
      }
      this.loading = true; // 显示加载状态
      this.loadingText = '数据查询中，请稍后...';

      // 向后台发送查询请求
      this.$http.post(`/charge/select/` + this.regId).then(res => {
        this.loading = false; // 关闭加载状态
        this.loadingText = '';
        const data = res.data.data[0]; // 获取返回数据中的第一个对象
        if (data) {
          this.careHistory = data; // 存储病例信息
          this.careOrders = data.careOrders || []; // 存储处方订单
          this.activeNames = this.careOrders.map((_, index) => index); // 默认展开所有处方
        } else {
          this.resetCurrentParams(); // 如果没有找到数据，重置页面数据
          this.$message.error('未找到相关信息');
        }
      }).catch(() => {
        this.$message.error('查询失败');
        this.loading = false; // 关闭加载状态
        this.loadingText = '';
      });
    },
    // 加载支付状态字典
    StatusName() {
      this.$http.get("/system/dict/data/type/his_order_details_status").then(resp => {
        this.payStatusOptions = resp.data.data;
      });
    },
    // 处理IC卡读取按钮的点击事件
    handleReadICCard() {
      this.$message.info('读取IC卡功能尚未实现');
    },
    // 状态格式化器，用于在表格中显示支付状态的文字描述
    statusFormatter(row) {
      let StatusName = "未知";
      this.payStatusOptions.forEach(item => {
        if (row.status === item.dictValue) {
          StatusName = item.dictLabel;
        }
      });
      return StatusName;
    },
    // 处理表格中处方项目的选中状态变化
    handleCareOrderItemSelectionChange(selection, coId) {
      const filteredSelection = selection.map(item => ({...item, coId}));

      this.itemObjs = this.itemObjs.filter(item => item.coId !== coId).concat(filteredSelection);
      this.computeAllAmount(); // 更新订单总金额
    },
    // 计算选中项目的总金额
    computeAllAmount() {
      this.allAmount = this.itemObjs.reduce((sum, item) => sum + item.amount, 0);
    },
    // 表格行样式的处理方法
    tableRowClassName({row, rowIndex}) {
      row.index = rowIndex;
    },
    // 全选操作处理
    handleSelectAll() {
      this.careOrders.forEach((order, index) => {
        const table = this.$refs.refTable[index];
        table.clearSelection(); // 清空当前选择
        table.toggleAllSelection(); // 全选当前表格中的所有项
      });
    },
    // 取消全选操作处理
    handleUnSelectAll() {
      this.careOrders.forEach((order, index) => {
        const table = this.$refs.refTable[index];
        table.clearSelection(); // 清空选择
      });
    },
    // 处理现金支付
    handlePayWithCash() {
      if (!this.careHistory.regId) {
        this.$message.warning('请输入挂号单ID查询');
      } else if (this.itemObjs.length === 0) {
        this.$message.warning('请选择要支付的项目');
      } else {
        const postObj = {
          orderAmount: this.allAmount, // 总金额
          chId: this.careHistory.chId, // 病历ID
          regId: this.careHistory.regId, // 挂号单ID
          patientName: this.careHistory.patientName, // 患者姓名
          createBy: this.careHistory.userName, // 创建人（医生姓名）
          orderChargeItemDtoList: this.itemObjs.map(item => ({
            itemId: item.itemId,
            coId: item.coId,
            itemName: item.itemName,
            itemPrice: item.price,
            itemNum: item.num,
            itemType: item.itemType,
            itemAmount: item.amount
          }))
        };
        console.log('postObj:', postObj);
        this.loading = true;
        this.loadingText = '订单创建并现金支付中';
        this.$confirm('是否确定创建订单并使用现金支付?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post('/charge/order/createNavigateCash', postObj)
              .then(response => {
                this.loading = false;
                this.loadingText = '';
                this.$message.success('支付成功');
                this.handleQuery(); // 支付成功后重新查询数据
              })
              .catch(() => {
                this.$message.error('支付失败');
                this.loading = false;
                this.loadingText = '';
              });
        }).catch(() => {
          this.loading = false;
          this.loadingText = '';
        });
      }
    },

    // 处理微信支付
    handlePayWithWx() {
      if (!this.careHistory.regId) {
        this.$message.warning('请输入挂号单ID查询');
        return;
      }
      if (this.itemObjs.length === 0) {
        this.$message.warning('请选择要支付的项目');
        return;
      }

      const postObj = {
        orderAmount: this.allAmount,
        chId: this.careHistory.chId,
        regId: this.careHistory.regId,
        patientName: this.careHistory.patientName,
        createBy: this.careHistory.userName,
        orderChargeItemDtoList: this.itemObjs.map(item => ({
          itemId: item.itemId,
          coId: item.coId,
          itemName: item.itemName,
          itemPrice: item.price,
          itemNum: item.num,
          itemType: item.itemType,
          itemAmount: item.amount
        }))
      };

      this.loading = true;
      this.$confirm('是否确定创建订单并使用微信支付?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post('/charge/order/createNavigateWenXin', postObj).then(res => {
          this.payObj = res.data.data;
          const orderId = res.data.data.orderId;
          this.openPay = true;
          this.startPolling(orderId); // 开始轮询支付状态
          this.startCountdown(); // 开始倒计时
          this.loading = false;
        }).catch(() => {
          this.$message.error('创建订单失败');
          this.loading = false;
        });
      }).catch(() => {
        this.loading = false;
      });
    },

    // 开始倒计时
    startCountdown() {
      this.countdown = 30; // 重置倒计时
      this.countdownTimer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.countdownTimer); // 停止倒计时
        }
      }, 1000); // 每秒减少1秒
    },

    // 开始轮询支付状态
    startPolling(orderId) {
      this.$http.post('/charge/order/queryPayStatus/' + orderId).then(res => {
        if (res.data.code === 200) {
          this.payResult.orderAmount = res.data.data.order_amount;
          this.payResult.codeUrl = res.data.data.code_url;
          this.payResult.orderId = res.data.data.orderId;

          this.intervalObj = setInterval(() => {
            this.handlePaymentSuccess(orderId);
          }, 2000); // 每2秒查询一次支付状态

          // 设置30秒后自动停止轮询和关闭弹窗
          this.autoCloseTimer = setTimeout(() => {
            this.closePayDialog();
          }, 30000); // 30秒
        } else {
          console.log('Payment not successful yet');
        }
      }).catch((error) => {
        console.error('Polling error:', error);
        clearInterval(this.intervalObj); // 停止轮询
      });
    },

    // 处理支付成功
    handlePaymentSuccess(orderId) {
      this.$http.post('/charge/order/queryPayStatus2/' + orderId).then(res => {
        if (res.data.code === 200) {
          this.$notify({
            title: '支付成功',
            message: `订单【${this.payResult.orderId}】支付成功`,
            type: 'success'
          });
          this.closePayDialog(); // 支付成功后关闭弹窗
        }
      }).catch(err => {
        console.error('Payment status query failed:', err);
      });
    },

    // 关闭支付弹窗和清理计时器
    closePayDialog() {
      clearInterval(this.intervalObj); // 停止轮询
      clearTimeout(this.autoCloseTimer); // 停止自动关闭计时器
      clearInterval(this.countdownTimer); // 停止倒计时
      this.openPay = false; // 关闭弹窗
      this.resetCurrentParams(); // 重置参数
    },

    // 处理支付弹窗关闭
    handleClose() {
      this.$confirm('您确定放弃支付吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.warning('您已放弃支付，可以回到收费查询列表里面再次支付');
        this.closePayDialog(); // 用户放弃支付时关闭弹窗
      }).catch(() => {
        this.$message.success('欢迎继续支付');
      });
    },
    // 重置当前数据
    resetCurrentParams() {
      this.careHistory = {}; // 清空病例信息
      this.careOrders = []; // 清空处方订单列表
      this.itemObjs = []; // 清空选中的处方项目
      this.activeNames = []; // 重置展开的处方列表
      this.allAmount = 0; // 重置总金额
      this.payObj = {}; // 清空支付对象
      this.payResult = {orderAmount: 0, codeUrl: "", orderId: ""}; // 清空支付结果
    }
  }
}
</script>

<style scoped>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
